package com.boe.hbd.server.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.ImageIO;

import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

public class ImageUtil {
	private static int width = 100;
	private static int height = 100;
	private static float quality = 1;

	public static void image(InputStream is, OutputStream sos)
			throws IOException {

		Image imageL = ImageIO.read(is);
		int new_w = 0, new_h = 0;
		int h = (int) imageL.getHeight(null);
		int w = (int) imageL.getWidth(null);
		if ((((double) w) > (double) width) || (((double) h) > (double) height)) {
			double rate = 0;
			if (w >= h) {
				rate = ((double) w) / (double) width;
			} else if (h > w) {
				rate = ((double) h) / (double) height;
			}
			new_w = (int) (((double) w) / rate);
			new_h = (int) (((double) h) / rate);
			BufferedImage tag = new BufferedImage(new_w, new_h,
					BufferedImage.TYPE_INT_RGB);
			tag.getGraphics().drawImage(imageL, 0, 0, new_w, new_h, null);
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
			JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
			jep.setQuality(quality, true);
			encoder.encode(tag, jep);
			sos.close();
			imageL.flush();
			is.close();
		}

	}

}
